package com.haizhi.redis;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: youfeng
 * Date: 2018-06-22
 * Time: 10:59
 */


public class RedisHandler {


    private JedisPool jedisPool;

    public RedisHandler(final GenericObjectPoolConfig poolConfig, final String host, int port,
                        int timeout, final String password, final int database) {
        jedisPool = new JedisPool(poolConfig, host, port, timeout, password, database);
    }


    /**
     * 获得jedis对象
     */
    public Jedis getJedisObject() {
        return jedisPool.getResource();
    }

    /**
     * 归还jedis对象
     */
    public void returnJedisOjbect(Jedis jedis) {
        if (jedis != null) {
            jedis.close();
        }
    }

    /**
     * 判断缓存是否存在
     *
     * @param key   主键
     * @param jedis redis句柄
     * @return 存在返回 True 不存在返回False
     */
    public boolean isCacheExist(String key, Jedis jedis) {
        return jedis.get(key) != null;
    }

    /**
     * 存储带有过期策略缓存
     *
     * @param key        主键
     * @param value      值
     * @param seconds 过期时间
     * @param jedis      redis句柄
     * @return 返回设置是否成功
     */
    public String saveCacheEx(String key, String value, Integer seconds, Jedis jedis) {
        return jedis.setex(key, seconds, value);
    }

    /**
     * 删除redis key
     *
     * @param key   主键
     * @param jedis 句柄
     * @return
     */
    public Long delCache(String key, Jedis jedis) {
        return jedis.del(key);
    }
}
